package controller

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"server/internal/app/api/admin/middleware"
	"server/internal/app/dto"
	"server/internal/app/service"
	"server/internal/core/server"
)

type AccountController struct {
	server.Controller
	authService      *service.AdminAuthService
	adminRbacService *service.AdminRbacService
}

func NewAccountController() *AccountController {
	return &AccountController{
		authService:      service.NewAdminAuthService(),
		adminRbacService: service.NewAdminRbacService(),
	}
}

func (ctl *AccountController) Register(ctx *gin.Context) {
	var req dto.AdminRegisterRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctl.Error(ctx, err)
		return
	}

	err := ctl.authService.Register(ctx, &req)
	if err != nil {
		ctl.Error(ctx, err)
		return
	}
	ctl.Success(ctx, nil)
}

func (ctl *AccountController) Login(ctx *gin.Context) {
	var req dto.AdminLoginRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctl.Error(ctx, err)
		return
	}

	meta := &dto.AdminLoginMeta{
		UserAgent: ctx.Request.UserAgent(),
		Referer:   ctx.Request.Referer(),
		IP:        ctx.ClientIP(),
	}

	resp, err := ctl.authService.Login(ctx, &req, meta)
	if err != nil {
		ctl.Error(ctx, err)
		return
	}

	ctl.Success(ctx, resp)
}

func (ctl *AccountController) Logout(ctx *gin.Context) {
	admin := middleware.GetCurrentAdmin(ctx)
	if admin != nil {
		err := ctl.authService.Logout(ctx, admin.Token)
		if err != nil {
			ctl.Error(ctx, err)
			return
		}
	}
	ctl.Success(ctx, nil)
}

func (ctl *AccountController) Profile(ctx *gin.Context) {
	adminID := middleware.GetCurrentAdminID(ctx)
	if adminID == 0 {
		ctl.Error(ctx, server.NewError(http.StatusUnauthorized, "未登录"))
		return
	}

	adminInfo, err := ctl.adminRbacService.GetAdminInfo(ctx, adminID, true)
	if err != nil {
		ctl.Error(ctx, err)
		return
	}
	ctl.Success(ctx, adminInfo)
}
